﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using PolePosition.v3.EntityFactory;

namespace PolePosition.v3.WcfService.MapServices
{
    public partial class AssetDistributionUpdateParents : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["ID"] != null)
                {
                    LabelAssetId.Text = "Asset #" + Request.QueryString["ID"] + ". Update Parents";
                    lnkAssetDistribution.NavigateUrl = "AssetDistribution.aspx?ID=" + Request.QueryString["ID"] ;
                    LoadAsset();
                }
            }
        }

        private void LoadAsset()
        {
            int id;

            if (int.TryParse(Request.QueryString["ID"], out id)) {
                var asset = UtilityAssetDistributionFactory.GetEntity(id);

                TextBoxParentAsset1.Text = asset.ParentAssetFk1.HasValue ? asset.ParentAssetFk1.Value.ToString() : string.Empty;
                TextBoxParentAsset2.Text = asset.ParentAssetFk2.HasValue ? asset.ParentAssetFk2.Value.ToString() : string.Empty;
                TextBoxParentAsset3.Text = asset.ParentAssetFk3.HasValue ? asset.ParentAssetFk3.Value.ToString() : string.Empty;
                TextBoxParentAsset4.Text = asset.ParentAssetFk4.HasValue ? asset.ParentAssetFk4.Value.ToString() : string.Empty;
                TextBoxParentAsset5.Text = asset.ParentAssetFk5.HasValue ? asset.ParentAssetFk5.Value.ToString() : string.Empty;
            }
        }

        protected void ButtonUpdateParents_Click(object sender, EventArgs e)
        {
            try 
            {
                CheckTextBoxes();
                CheckAssetsIds();
                UpdateParentAssets();
                
                LabelErrorMessage.Visible = false;
                LabelSuccesfullMessage.Visible = true;
                }
            catch(Exception exc)
            {
                LabelErrorMessage.Text = exc.Message;
                LabelErrorMessage.Visible = true;
                LabelSuccesfullMessage.Visible = false;
            }
        }

        private void CheckTextBoxes()
        {
            if (TextBoxParentAsset1.Text.Trim().Equals(string.Empty) &&
                TextBoxParentAsset2.Text.Trim().Equals(string.Empty) &&
                TextBoxParentAsset3.Text.Trim().Equals(string.Empty) &&
                TextBoxParentAsset4.Text.Trim().Equals(string.Empty) &&
                TextBoxParentAsset5.Text.Trim().Equals(string.Empty))
                throw new Exception("All parent text box are empty. At least, one parent asset should be filled.");
        }

        private void UpdateParentAssets()
        {
            var xmlWriterSettings = new XmlWriterSettings();
            xmlWriterSettings.Encoding = new UTF8Encoding(false);
            xmlWriterSettings.ConformanceLevel = ConformanceLevel.Document;
            xmlWriterSettings.Indent = true;

            var memoryStream = new MemoryStream();
            var xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings);
            xmlWriter.WriteStartElement("assets");
            xmlWriter.WriteStartElement("asset");

            xmlWriter.WriteAttributeString("id", Request.QueryString["ID"]);
            xmlWriter.WriteElementString("parentAssetFk1", TextBoxParentAsset1.Text.Trim());
            xmlWriter.WriteElementString("parentAssetFk2", TextBoxParentAsset2.Text.Trim());
            xmlWriter.WriteElementString("parentAssetFk3", TextBoxParentAsset3.Text.Trim());
            xmlWriter.WriteElementString("parentAssetFk4", TextBoxParentAsset4.Text.Trim());
            xmlWriter.WriteElementString("parentAssetFk5", TextBoxParentAsset5.Text.Trim());

            xmlWriter.WriteEndElement();
            xmlWriter.WriteEndElement();
            xmlWriter.Flush();

            string xmlString = Encoding.UTF8.GetString(memoryStream.ToArray());

            //Send xmlString to update the parent assets.
            UtilityAssetDistributionFactory.UpdateParentsByXml(xmlString);
        }

        private void CheckAssetsIds()
        {
            int utilityId = 0;
            var assetIds = new List <int>();

            if (Request.QueryString["ID"] != null)
                utilityId = int.Parse(Request.QueryString["UtilityId"]);

            if (!TextBoxParentAsset1.Text.Trim().Equals(string.Empty))
                assetIds.Add(int.Parse(TextBoxParentAsset1.Text));

            if (!TextBoxParentAsset2.Text.Trim().Equals(string.Empty))
                assetIds.Add(int.Parse(TextBoxParentAsset2.Text));

            if (!TextBoxParentAsset3.Text.Trim().Equals(string.Empty))
                assetIds.Add(int.Parse(TextBoxParentAsset3.Text));

            if (!TextBoxParentAsset4.Text.Trim().Equals(string.Empty))
                assetIds.Add(int.Parse(TextBoxParentAsset4.Text));

            if (!TextBoxParentAsset5.Text.Trim().Equals(string.Empty))
                assetIds.Add(int.Parse(TextBoxParentAsset5.Text));

            int [] invalidIds = UtilityAssetDistributionFactory.ValidateDistributionAssetId(utilityId, assetIds.ToArray());

            if (invalidIds.Length > 0) 
            {
                var errorMessage = "Some asset ids are invalid: ";

                foreach (int i in invalidIds)
                    errorMessage += i + ",";

                throw new Exception(errorMessage.Remove(errorMessage.Length - 1));
            }
            
        }
    }
}
